#include "Texture.h"
#include <windows.h>
#include "OpenGL.h"
#include "stdio.h"

unsigned int Texture::building;
unsigned int Texture::ground;
unsigned int Texture::skyBox;

int Texture::LoadTexture(wchar_t *fileName)
{	
	FILE *file;
	_wfopen_s(&file, fileName, L"r");
	if(file == NULL)
		return -1;

	char *bmp, byte;
	BITMAPINFOHEADER bmpInfoh;
	BITMAPFILEHEADER bmpFileh;
	fread(&bmpFileh, sizeof(BITMAPFILEHEADER), 1, file);
	if(bmpFileh.bfType != 19778)
		return false;

	fread(&bmpInfoh, sizeof(BITMAPINFOHEADER), 1, file);	
	bmp = new char[bmpFileh.bfSize - bmpFileh.bfOffBits];
	if(!bmp)
		return -1;	
	fread(bmp, 1, bmpFileh.bfSize - bmpFileh.bfOffBits, file);		
	
	for(int i = 0; i < bmpInfoh.biHeight * bmpInfoh.biWidth; i++)
	{
		byte = bmp[3 * i];
		bmp[3 * i] = bmp[3 * i + 2];
		bmp[3 * i + 2] = byte;
	}
	unsigned int index;
	glGenTextures(1, &index);
	glBindTexture(GL_TEXTURE_2D, index);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR);	
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);	
	gluBuild2DMipmaps(GL_TEXTURE_2D, 3, bmpInfoh.biWidth, bmpInfoh.biHeight, GL_RGB, GL_UNSIGNED_BYTE, bmp);	
	//glTexImage2D(GL_TEXTURE_2D, 0, 3, bmpInfoh.biWidth, bmpInfoh.biHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, bmp);
	delete[] bmp;
	bmp = NULL;
	fclose(file);	
	return index;
}

void Texture::Load(void)
{
	building = LoadTexture(L"Textures//Building.bmp");
	ground = LoadTexture(L"Textures//Ground.bmp");
	skyBox = LoadTexture(L"Textures//SkyBox.bmp");
}

void Texture::Delete(void)
{
	glDeleteTextures(1, &building);
	glDeleteTextures(1, &ground);
	glDeleteTextures(1, &skyBox);
}

unsigned int Texture::Building(void)
{
	return building;
}
unsigned int Texture::Ground(void)
{
	return ground;
}
unsigned int Texture::SkyBox(void)
{
	return skyBox;
}